package com.wenx.guava;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class GuavaCache {

    static LoadingCache<String,String> userNameCache =
            CacheBuilder.newBuilder()
                    .maximumSize(100L)  //缓存大小
                    .expireAfterAccess(5, TimeUnit.SECONDS)  //5s没有访问则失效
                    .build(new CacheLoader<String, String>() {
                        @Override
                        public String load(String s) {
                            Random r = new Random();
                            int i = r.nextInt(100);
                            return "你好，我是"+s+"，编号："+i;
                        }
                    });

    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s = sc.nextLine();
            String s1 = userNameCache.get(s);
            System.out.println("s1 = " + s1);

        }

    }

}
